package com.koala.web.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.koala.common.constant.Constants;
import com.koala.common.core.domain.entity.SysUser;
import com.koala.common.core.domain.model.LoginUser;
import com.koala.common.core.redis.RedisCache;
import com.koala.common.exception.ServiceException;
import com.koala.common.exception.user.UserPasswordNotMatchException;
import com.koala.common.utils.DateUtils;
import com.koala.common.utils.MessageUtils;
import com.koala.framework.manager.AsyncManager;
import com.koala.framework.manager.factory.AsyncFactory;
import com.koala.framework.security.context.AuthenticationContextHolder;
import com.koala.framework.web.service.SysLoginService;
import com.koala.framework.web.service.TokenService;
import com.koala.system.service.ISysConfigService;
import com.koala.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.koala.web.mapper.UserMapper;
import com.koala.web.domain.User;
import com.koala.web.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

/**
 * 用户，存储用户信息Service业务层处理
 * 
 * @author koala
 * @date 2025-11-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysLoginService loginService;

    @Resource
    private IUserService iUserService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户，存储用户信息
     * 
     * @param userId 用户，存储用户信息主键
     * @return 用户，存储用户信息
     */
    @Override
    public User selectUserByUserId(String userId)
    {
        return userMapper.selectUserByUserId(userId);
    }

    /**
     * 查询用户，存储用户信息列表
     * 
     * @param user 用户，存储用户信息
     * @return 用户，存储用户信息
     */
    @Override
    public List<User> selectUserList(User user)
    {
        return userMapper.selectUserList(user);
    }

    /**
     * 新增用户，存储用户信息
     * 
     * @param user 用户，存储用户信息
     * @return 结果
     */
    @Override
    public int insertUser(User user)
    {
        user.setCreateTime(DateUtils.getNowDate());
        user.setUserId(Long.parseLong(IdUtil.getSnowflakeNextIdStr()));
        user.setUserName("123");
        return userMapper.insertUser(user);
    }

    /**
     * 修改用户，存储用户信息
     * 
     * @param user 用户，存储用户信息
     * @return 结果
     */
    @Override
    public int updateUser(User user)
    {
        user.setUpdateTime(DateUtils.getNowDate());
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除用户，存储用户信息
     * 
     * @param userIds 需要删除的用户，存储用户信息主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserIds(String[] userIds)
    {
        return userMapper.deleteUserByUserIds(userIds);
    }

    /**
     * 删除用户，存储用户信息信息
     * 
     * @param userId 用户，存储用户信息主键
     * @return 结果
     */
    @Override
    public int deleteUserByUserId(String userId)
    {
        return userMapper.deleteUserByUserId(userId);
    }

    @Override
    public User login(LoginUser user) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String username = user.getUsername();
        String password = user.getPassword();

        User serviceOne = iUserService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUserName, username)
        );

        if (serviceOne != null && passwordEncoder.matches(password, serviceOne.getPassword())) {
            // 生成token
            // 此处为了兼容若依系统设置了全部权限
            user.setPermissions(new HashSet<String>(){{add("*:*:*");}});
            user.setUserId(serviceOne.getUserId());
            String token = tokenService.createToken(user);
            serviceOne.setToken(token);
            return serviceOne;
        }

        throw new UserPasswordNotMatchException();
    }


    @Override
    public boolean register(User user) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        User one = iUserService.lambdaQuery().eq(User::getUserName, user.getUserName()).one();
        if (one != null) throw new ServiceException("账户名已存在");

        User two = iUserService.lambdaQuery().eq(User::getEmail, user.getEmail()).one();
        if (two != null) throw new ServiceException("邮箱已注册");

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return iUserService.save(user);
    }

    @Override
    public boolean modifyPassword(User user) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        User sysUser = iUserService.getById(user.getUserId());
        if (sysUser != null) {
            String oldPassword =  passwordEncoder.encode(user.getPassword());
            if (oldPassword.equals(sysUser.getPassword())) {
                sysUser.setPassword(passwordEncoder.encode(user.getNewPassword()));

                return iUserService.updateUser(sysUser) > 0;
            }
            throw new UserPasswordNotMatchException();
        }

        throw new ServiceException("用户不存在！");
    }
}
